package com.tqjc.system.system.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tqjc.system.common.constant.GlobalConstant;
import com.tqjc.system.common.constant.SQLConstant;
import com.tqjc.system.common.entity.VO.AreaInfoVO;
import com.tqjc.system.common.entity.VO.FatherAreaInfoVO;
import com.tqjc.system.common.exception.AddTaskException;
import com.tqjc.system.system.dao.SysAreaInfoDao;
import com.tqjc.system.system.entity.SysAreaInfoEntity;
import com.tqjc.system.system.entity.SysMaterialInfoEntity;
import com.tqjc.system.system.service.SysAreaInfoService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 86195
 * @version 1.0
 * @description 库区信息服务类
 * @date 2023/10/17 14:31
 */
@Service("SysAreaInfoService")
@Slf4j
public class SysAreaInfoServiceImpl extends ServiceImpl<SysAreaInfoDao, SysAreaInfoEntity> implements SysAreaInfoService {
    @Override
    public int queryMaterialNum(String spanNo, List<String> taskMaterialList) {
        return baseMapper.selectCount(new QueryWrapper<SysAreaInfoEntity>().select("distinct stock_material_no").lambda()
                .eq(SysAreaInfoEntity::getSpanNo,spanNo).isNotNull(SysAreaInfoEntity::getParentId)
                .in(SysAreaInfoEntity::getStockMaterialNo,taskMaterialList));
    }

    @Override
    public SysAreaInfoEntity queryMaterialNoIndex(String materialNo,String spanNo,int areaNum) {
        return baseMapper.selectOne(new LambdaQueryWrapper<SysAreaInfoEntity>().eq(SysAreaInfoEntity::getAreaNum,areaNum)
                .eq(SysAreaInfoEntity::getSpanNo,spanNo).eq(SysAreaInfoEntity::getStockMaterialNo,materialNo)
                .eq(SysAreaInfoEntity::getIsEffective,GlobalConstant.AREA_STATUS_EFFECTIVE).orderByDesc(SysAreaInfoEntity::getIndexLeftTopX)
                .last(SQLConstant.SQL_LIMIT_1));
    }


    @Override
    public SysAreaInfoEntity queryMaterialNoIndex(String materialNo,String spanNo) {
        return baseMapper.selectOne(new LambdaQueryWrapper<SysAreaInfoEntity>().eq(SysAreaInfoEntity::getSpanNo,spanNo)
                .eq(SysAreaInfoEntity::getStockMaterialNo,materialNo).eq(SysAreaInfoEntity::getIsEffective,GlobalConstant.AREA_STATUS_EFFECTIVE)
                .isNotNull(SysAreaInfoEntity::getParentId).orderByDesc(SysAreaInfoEntity::getIndexLeftTopX)
                .last(SQLConstant.SQL_LIMIT_1));
    }

    @Override
    public  IPage<SysAreaInfoEntity> getListByPage(Page<SysAreaInfoEntity> pageEntity, AreaInfoVO areaInfoVO) {
        LambdaQueryWrapper<SysAreaInfoEntity> queryWrapper = new LambdaQueryWrapper<SysAreaInfoEntity>()
                .eq(StringUtils.isNotEmpty(areaInfoVO.getSpanNo()), SysAreaInfoEntity::getSpanNo, areaInfoVO.getSpanNo())
                .eq(StringUtils.isNotEmpty(areaInfoVO.getAreaName()), SysAreaInfoEntity::getAreaName, areaInfoVO.getAreaName())
                .orderByDesc(SysAreaInfoEntity::getSpanNo, SysAreaInfoEntity::getUpdateDate);
        return super.page(pageEntity,queryWrapper);
    }

    @Override
    public int updateInfo(AreaInfoVO areaInfoVO) {
        SysAreaInfoEntity updateEntity = SysAreaInfoEntity.builder().idKey(areaInfoVO.getIdKey()).isEffective(areaInfoVO.getIsEffective())
                .areaName(areaInfoVO.getAreaName()).stockMaterialName(areaInfoVO.getMaterialName()).indexLeftTopX(areaInfoVO.getIndexLeftTopX())
                .indexLeftTopY(areaInfoVO.getIndexLeftTopY()).indexRightBottomX(areaInfoVO.getIndexRightBottomX()).indexRightBottomY(areaInfoVO.getIndexRightBottomY())
                .stockMaterialNo(areaInfoVO.getMaterialNo()).build();
        return baseMapper.updateById(updateEntity);
    }

    @Override
    public List<SysAreaInfoEntity> getList(AreaInfoVO areaInfoVO) {
        LambdaQueryWrapper<SysAreaInfoEntity> queryWrapper = new LambdaQueryWrapper<SysAreaInfoEntity>()
                .eq(StringUtils.isNotEmpty(areaInfoVO.getSpanNo()), SysAreaInfoEntity::getSpanNo, areaInfoVO.getSpanNo())
                .eq(StringUtils.isNotEmpty(areaInfoVO.getAreaName()), SysAreaInfoEntity::getAreaName, areaInfoVO.getAreaName())
                .orderByDesc(SysAreaInfoEntity::getSpanNo)
//                .orderByAsc(SysAreaInfoEntity::getIndexLeftTopX);
                .last(",IF(ISNULL(index_left_top_x),184000,1), index_left_top_x");
        return baseMapper.selectList(queryWrapper);
    }

    @Override
    public FatherAreaInfoVO getFatherAreaInfo(String idkey) {
        return baseMapper.getFatherAreaInfo(idkey);

    }

    @Override
    public boolean addAreaNum(FatherAreaInfoVO fatherAreaInfoVO) {
        try {

            int addAreaNum = fatherAreaInfoVO.getAddAreaNum();
            SysAreaInfoEntity sysAreaInfoEntity = SysAreaInfoEntity.builder().areaNum(fatherAreaInfoVO.getAddAreaNum())
                    .isEffective(GlobalConstant.AREA_STATUS_UNEFFECTIVE).parentId(fatherAreaInfoVO.getParentId())
                    .spanNo(fatherAreaInfoVO.getSpanNo()).spanName(fatherAreaInfoVO.getSpanName()).build();
            List<SysAreaInfoEntity> list = new ArrayList<>(addAreaNum);
            for(int i = 0;i < addAreaNum;i++){
                list.add(sysAreaInfoEntity);
            }
            return this.saveBatch(list);
        } catch (Exception e){
            log.error("新增库区保存集合失败",e);
        }
        return false;
    }

    @Override
    public boolean addChildArea(AreaInfoVO areaInfoVO) throws AddTaskException {
        try {
            String parentId = areaInfoVO.getParentId();
            SysAreaInfoEntity sysAreaInfoEntity = baseMapper.selectById(parentId);
            Integer indexLeftTopX = areaInfoVO.getIndexLeftTopX();
            Integer indexRightBottomX = areaInfoVO.getIndexRightBottomX();
            Integer indexRightBottomY = areaInfoVO.getIndexRightBottomY();
            Integer indexLeftTopY = areaInfoVO.getIndexLeftTopY();
            if(indexLeftTopX <= indexRightBottomX || indexLeftTopY <= indexRightBottomY){
                log.error("子区域划分有误，左上坐标应大于右下坐标");
                throw new AddTaskException("子区域划分有误，左上坐标应大于右下坐标");
            }

            if(indexLeftTopX <= sysAreaInfoEntity.getIndexLeftTopX() && indexRightBottomX >= sysAreaInfoEntity.getIndexRightBottomX()
                    && indexRightBottomY >= sysAreaInfoEntity.getIndexRightBottomY() && indexLeftTopY <= sysAreaInfoEntity.getIndexLeftTopY()){
                //检验子区域坐标是否满足父区域范围
                List<SysAreaInfoEntity> list = baseMapper.selectList(new LambdaQueryWrapper<SysAreaInfoEntity>().eq(SysAreaInfoEntity::getParentId, parentId)
                        .eq(SysAreaInfoEntity::getIsEffective,GlobalConstant.AREA_STATUS_EFFECTIVE));
                if(CollectionUtil.isNotEmpty(list)){
                    for (SysAreaInfoEntity item : list) {
                        if( ( indexLeftTopX < item.getIndexLeftTopX()  && indexLeftTopX > item.getIndexRightBottomX()) ||
                                (indexRightBottomX < item.getIndexLeftTopX()  && indexRightBottomX > item.getIndexRightBottomX()) ){
                            log.error("子区域划分有误,X范围与其他子区域重复");
                            throw new AddTaskException("子区域划分有误,X范围与其他子区域重复");
                        }

                        if( ( indexRightBottomY < item.getIndexLeftTopY()  && indexRightBottomY > item.getIndexRightBottomY()) ||
                                (indexLeftTopY < item.getIndexLeftTopY()  && indexLeftTopY > item.getIndexRightBottomY()) ){
                            log.error("子区域划分有误,Y范围与其他子区域重复");
                            throw new AddTaskException("子区域划分有误,Y范围与其他子区域重复");
                        }

                    }
                }

                int i = this.updateInfo(areaInfoVO);
                if(i > 0){
                    return true;
                }

            } else {
                log.error("子区域划分有误，子区域范围应该在父区域范围内");
                throw new AddTaskException("子区域划分有误，子区域范围不应该大于父区域范围");
            }
        } catch (Exception e){
            log.error("addChildArea方法异常");
            throw e;
        }
        return false;
    }

    @Override
    public boolean delChildArea(String id) {
        int i = baseMapper.deleteById(id);
        if(i > 0){
            return true;
        }
        return false;
    }


}
